const { Paragraph, TextRun, HeadingLevel, PageBreak, PageOrientation, SectionType, AlignmentType } = require("docx");
const { generateFields } = require("../fields");

// 生成所有章节
function generateSections(sections) {
    const allSections = [];
    let currentSectionElements = [];
    let currentSectionProperties = {
        page: {
            size: {
                orientation: PageOrientation.PORTRAIT
            }
        }
    };
    
    sections.forEach((section, sectionIndex) => {
        // 处理两种数据结构：完整配置或简化配置
        const sectionData = section.sectionId || section;
        const sectionName = sectionData.name;
        const forms = sectionData.forms || section.forms || [];
        
        // 检查这个章节是否有横向表单
        const hasLandscapeForms = forms.some(form => 
            form.config?.formConfig?.pageOrientation === 'landscape'
        );
        
        // 如果章节中没有横向表单，直接添加章节标题到当前section
        if (!hasLandscapeForms) {
            // 章节标题 (一级标题)
            const align = (section.config?.titleAlign || sectionData.config?.titleAlign) === 'left' ? AlignmentType.LEFT : AlignmentType.CENTER;
            currentSectionElements.push(new Paragraph({
                heading: HeadingLevel.HEADING_1,
                alignment: align,
                children: [
                    new TextRun(`${sectionIndex + 1}. ${sectionName}`),
                ],
            }));
            
            // 处理所有表单（都是纵向的）
            forms.forEach((form, formIndex) => {
                if (!form.config.fields) {
                    return;
                }
                
                const pageIsolation = form.config?.formConfig?.pageIsolation === true;
                const elements = [];
                
                // 检查表单中是否存在样式为2的粘贴单
                const hasStyle2PasteUnit = form.config.fields.some(
                    field => field.type === 'pasteUnit' && field.value?.styleType === 'style2'
                );
                
                // 如果存在样式2粘贴单且不是单页隔离，添加分页符
                if (hasStyle2PasteUnit && !pageIsolation) {
                    elements.push(new Paragraph({ children: [new PageBreak()] }));
                }
                
                // 如果设置了单页隔离：非本章节第一个表单才在前面分页，
                // 以确保当第一个表单为单页时，章节标题与该表单在同一页。
                if (pageIsolation && formIndex !== 0) {
                    elements.push(new Paragraph({ children: [new PageBreak()] }));
                }
                
                // 表单标题 (二级标题) - 支持隐藏
                const hideTitle = form.config?.formConfig?.hideTitle === true;
                if (!hideTitle) {
                    elements.push(new Paragraph({
                        heading: HeadingLevel.HEADING_2,
                        children: [
                            new TextRun(`${sectionIndex + 1}.${formIndex + 1} ${form.name}`),
                        ],
                    }));
                }
                
                // 生成字段
                elements.push(...generateFields(form.config.fields, 0));
                
                // 如果设置了单页隔离，在结束时添加分页符
                if (pageIsolation) {
                    elements.push(new Paragraph({ children: [new PageBreak()] }));
                }
                
                // 添加到当前section
                currentSectionElements.push(...elements);
            });
        } else {
            // 章节中有横向表单，需要特殊处理
            let chapterTitleAdded = false;
            
            forms.forEach((form, formIndex) => {
                if (!form.config.fields) {
                    return;
                }
                
                const pageIsolation = form.config?.formConfig?.pageIsolation === true;
                const isLandscape = form.config?.formConfig?.pageOrientation === 'landscape';
                
                if (isLandscape) {
                    // 横向表单：保存当前section（如果有内容），然后创建横向section
                    if (currentSectionElements.length > 0) {
                        allSections.push({
                            properties: currentSectionProperties,
                            children: [...currentSectionElements]
                        });
                        currentSectionElements = [];
                    }
                    
                    // 创建横向表单的独立section，包含章节标题
                    const landscapeElements = [];
                    
                    // 如果章节标题还没有添加，添加章节标题
                    if (!chapterTitleAdded) {
                        const align = (section.config?.titleAlign || sectionData.config?.titleAlign) === 'left' ? AlignmentType.LEFT : AlignmentType.CENTER;
                        landscapeElements.push(new Paragraph({
                            heading: HeadingLevel.HEADING_1,
                            alignment: align,
                            children: [
                                new TextRun(`${sectionIndex + 1}. ${sectionName}`),
                            ],
                        }));
                        chapterTitleAdded = true;
                    }
                    
                    // 检查表单中是否存在样式为2的粘贴单
                    const hasStyle2PasteUnit = form.config.fields.some(
                        field => field.type === 'pasteUnit' && field.value?.styleType === 'style2'
                    );
                    
                    // 如果存在样式2粘贴单，添加分页符
                    if (hasStyle2PasteUnit) {
                        landscapeElements.push(new Paragraph({ children: [new PageBreak()] }));
                    }
                    
                    // 表单标题 (二级标题) - 支持隐藏
                    const hideTitle = form.config?.formConfig?.hideTitle === true;
                    if (!hideTitle) {
                        landscapeElements.push(new Paragraph({
                            heading: HeadingLevel.HEADING_2,
                            children: [
                                new TextRun(`${sectionIndex + 1}.${formIndex + 1} ${form.name}`),
                            ],
                        }));
                    }
                    
                    // 生成字段
                    landscapeElements.push(...generateFields(form.config.fields, 0));
                    
                    // 创建横向section
                    allSections.push({
                        properties: {
                            type: SectionType.NEXT_PAGE,
                            page: {
                                size: {
                                    orientation: PageOrientation.LANDSCAPE
                                }
                            }
                        },
                        children: landscapeElements
                    });
                    
                    // 重置当前section为纵向
                    currentSectionProperties = {
                        page: {
                            size: {
                                orientation: PageOrientation.PORTRAIT
                            }
                        }
                    };
                } else {
                    // 纵向表单：添加到当前section
                    const elements = [];
                    
                    // 如果章节标题还没有添加，添加章节标题
                    if (!chapterTitleAdded) {
                        elements.push(new Paragraph({
                            heading: HeadingLevel.HEADING_1,
                            children: [
                                new TextRun(`${sectionIndex + 1}. ${sectionName}`),
                            ],
                        }));
                        chapterTitleAdded = true;
                    }
                    
                    // 检查表单中是否存在样式为2的粘贴单
                    const hasStyle2PasteUnit = form.config.fields.some(
                        field => field.type === 'pasteUnit' && field.value?.styleType === 'style2'
                    );
                    
                    // 如果存在样式2粘贴单且不是单页隔离，添加分页符
                    if (hasStyle2PasteUnit && !pageIsolation) {
                        elements.push(new Paragraph({ children: [new PageBreak()] }));
                    }
                    
                    // 单页：若该表单是本章节第一个表单（即刚添加标题），不在标题与表单之间分页
                    if (pageIsolation && chapterTitleAdded) {
                        // chapterTitleAdded 为 true 表示标题已存在，
                        // 但此处可能是本章节后续表单（标题此前已添加）。
                        // 因此需用 formIndex 判断是否第一个表单。
                        if (formIndex !== 0) {
                            elements.push(new Paragraph({ children: [new PageBreak()] }));
                        }
                    }
                    
                    // 表单标题 (二级标题) - 支持隐藏
                    const hideTitle = form.config?.formConfig?.hideTitle === true;
                    if (!hideTitle) {
                        elements.push(new Paragraph({
                            heading: HeadingLevel.HEADING_2,
                            children: [
                                new TextRun(`${sectionIndex + 1}.${formIndex + 1} ${form.name}`),
                            ],
                        }));
                    }
                    
                    // 生成字段
                    elements.push(...generateFields(form.config.fields, 0));
                    
                    // 如果设置了单页隔离，在结束时添加分页符
                    if (pageIsolation) {
                        elements.push(new Paragraph({ children: [new PageBreak()] }));
                    }
                    
                    // 添加到当前section
                    currentSectionElements.push(...elements);
                }
            });
        }
    });
    
    // 如果最后还有未保存的section内容，保存它
    if (currentSectionElements.length > 0) {
        allSections.push({
            properties: currentSectionProperties,
            children: currentSectionElements
        });
    }
    
    return allSections;
}

// 生成表单 - 保持向后兼容
function generateForms(forms, sectionNumber) {
    return forms.flatMap((form, formIndex) => {
        if (!form.config.fields) {
            return [];
        }
        
        const elements = [];
        
        // 页面方向 & 单页设置
        const pageIsolation = form.config?.formConfig?.pageIsolation === true;
        const isLandscape = form.config?.formConfig?.pageOrientation === 'landscape';

        // 如果需要横向或单页隔离，添加分页符
        if (isLandscape || pageIsolation) {
            elements.push(new Paragraph({ children: [new PageBreak()] }));
        }

        // 检查表单中是否存在样式为2的粘贴单
        const hasStyle2PasteUnit = form.config.fields.some(
            field => field.type === 'pasteUnit' && field.value?.styleType === 'style2'
        );
        
        // 如果存在，则在表单前添加分页符
        if (hasStyle2PasteUnit && !pageIsolation && !isLandscape) {
            elements.push(new Paragraph({ children: [new PageBreak()] }));
        }
        
        // 表单标题 (二级标题) - 支持隐藏
        const hideTitle = form.config?.formConfig?.hideTitle === true;
        if (!hideTitle) {
            elements.push(new Paragraph({
                heading: HeadingLevel.HEADING_2,
                children: [
                    new TextRun(`${sectionNumber}.${formIndex + 1} ${form.name}`),
                ],
            }));
        }
        
        // 生成字段
        elements.push(...generateFields(form.config.fields, 0));
        
        // 如果是横向或单页隔离，在结束时添加分页符
        if (isLandscape || pageIsolation) {
            elements.push(new Paragraph({ children: [new PageBreak()] }));
        }

        return elements;
    });
}

module.exports = {
    generateSections,
    generateForms
}; 